package com.sgj.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.sgj.common.constant.RabbitConstant;
import com.sgj.common.exception.RRException;
import com.sgj.common.to.mq.OrderTo;
import com.sgj.common.to.mq.StockDetailTo;
import com.sgj.common.to.mq.StockLockedTo;
import com.sgj.common.vo.OrderConfirmVo.*;
import com.sgj.common.vo.OrderVo;
import com.sgj.common.vo.SkuHasStockVo;
import com.sgj.common.utils.R;
import com.sgj.common.vo.SkuWareHasStock;
import com.sgj.common.vo.WareSkuLockVo;
import com.sgj.common.exception.NoStockException;
import com.sgj.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.sgj.gulimall.ware.entity.WareOrderTaskEntity;
import com.sgj.gulimall.ware.feign.OrderFeignService;
import com.sgj.gulimall.ware.feign.ProductFeignService;
import com.sgj.gulimall.ware.service.WareOrderTaskDetailService;
import com.sgj.gulimall.ware.service.WareOrderTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.common.utils.PageUtils;
import com.sgj.common.utils.Query;

import com.sgj.gulimall.ware.dao.WareSkuDao;
import com.sgj.gulimall.ware.entity.WareSkuEntity;
import com.sgj.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 如果没有库存记录则新增
        List<WareSkuEntity> entities = baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (Objects.isNull(entities) || entities.size() == 0) {
            WareSkuEntity wareSkuEntity = WareSkuEntity.builder()
                    .skuId(skuId)
                    .stock(skuNum)
                    .wareId(wareId)
                    .stockLocked(0)
                    .build();
            // 远程查询sku名称，如果失败，事务无须回滚
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            baseMapper.insert(wareSkuEntity);
        } else {
            baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVos = skuIds.stream()
                .map(skuId -> {
                    // 查询当前 sku 的总库存量
                    Long count = baseMapper.getSkuStock(skuId);
                    SkuHasStockVo vo = SkuHasStockVo.builder()
                            .skuId(skuId)
                            .hasStock(Objects.isNull(count) ? false : count > 0)
                            .build();
                    return vo;
                }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        // 保存库存工作单详情
        WareOrderTaskEntity taskEntity = WareOrderTaskEntity.builder()
                .orderSn(vo.getOrderSn())
                .build();
        orderTaskService.save(taskEntity);

        // 根据下单地址寻找就近仓库锁定库存
        // 找到每个商品在哪些仓库有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = SkuWareHasStock.builder()
                    .skuId(item.getSkuId())
                    .num(item.getCount())
                    // 查询商品在哪有库存
                    .wareId(baseMapper.listWareIdHasSkuStock(item.getSkuId()))
                    .build();
            return stock;
        }).collect(Collectors.toList());

        // 锁定库存
        for (SkuWareHasStock stock : collect) {
            Boolean skuStocked = false;
            if (CollectionUtils.isEmpty(stock.getWareId())) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(stock.getSkuId());
            }
            for (Long wareId : stock.getWareId()) {
                Long count = baseMapper.lockSkuStock(stock.getSkuId(), wareId, stock.getNum());
                if (count == 1L) {
                    skuStocked = true;
                    //TODO 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity taskDetailEntity = WareOrderTaskDetailEntity.builder()
                            .skuId(stock.getSkuId())
                            .skuName("")
                            .skuNum(stock.getNum())
                            .taskId(taskEntity.getId())
                            .wareId(wareId)
                            .lockStatus(1)
                            .build();
                    orderTaskDetailService.save(taskDetailEntity);

                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, stockDetailTo);
                    StockLockedTo lockedTo = StockLockedTo.builder()
                            .id(taskEntity.getId())
                            .detail(stockDetailTo)
                            .build();
                    rabbitTemplate.convertAndSend(RabbitConstant.STOCK_EXCHANGE, RabbitConstant.ROUTING_KEY_LOCKED, lockedTo);
                    break;
                }
            }
            if (!skuStocked) {
                // 库存都没有锁定住
                throw new NoStockException(stock.getSkuId());
            }
        }
        return true;
    }

    @Override
    public void unLockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        Long detailId = detail.getId();
        // 查询数据库关于这个订单的锁定库存信息
        WareOrderTaskDetailEntity taskDetailEntity = orderTaskDetailService.getById(detailId);
        if (Objects.nonNull(taskDetailEntity)){
            // 解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                // 订单数据返回成功
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {});
                if (Objects.isNull(orderVo) || orderVo.getStatus() == 4) {
                    // 订单已被取消，可以解锁库存
                    if (taskDetailEntity.getLockStatus() == 1) {
                        // 已锁定，未解锁才可解锁库存
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            } else {
                // 抛出异常让监听队列拒绝消息
                throw new RRException("远程服务失败");
            }
        }
    }

    @Override
    public void unLockStock(OrderTo to) {
        // 查询订单最新的状态，防止重复解锁
        WareOrderTaskEntity task = orderTaskService.getOrderTaskByOrderSn(to.getOrderSn());
        // 根据工作单找到所有未解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", task.getId())
                        .eq("lock_status", 1)
        );
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum(), entity.getId());
        }
    }

    /**
     * 解锁库存
     * @param skuId
     * @param wareId
     * @param num
     * @param taskDetailId
     */
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        // 库存解锁
        baseMapper.unlockStock(skuId, wareId, num);
        // 库存工作单状态变更
        WareOrderTaskDetailEntity taskDetailEntity = WareOrderTaskDetailEntity.builder()
                .id(taskDetailId)
                .lockStatus(2)
                .build();
        orderTaskDetailService.updateById(taskDetailEntity);
    }

}